//
//  ChatViewController.m
//  TIMChat
//
//  Created by AlexiChen on 16/2/23.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "ChatViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "XFEmotion.h"
#import "MyChatToolBarView.h"
#import "MyUIDefine.h"
#import "MyMoreView.h"
#import "MHChatViewModel.h"
#import "MHComposeViewModel.h"
#import "MHVideoRecordViewModel.h"
#import "MHChatGroupHeaderView.h"
#import "MHCircleSimpleInfo.h"
#import "MHMomentDetailViewModel.h"
#import "MHAskViewModel.h"
#import "MHSettingCircleViewModel.h"
#import "MHSettingCirleInfoViewController.h"
#import "MHCircleMemberViewController.h"
@interface ChatViewController ()
@property(nonatomic, strong) MHChatViewModel *viewModel;
@property (nonatomic, strong) MyChatToolBarView *toolBar;
@property (nonatomic, strong) UIImagePickerController *imagePicker;

@end


#define kLoadDataPageSiez 50
@implementation ChatViewController
@dynamic viewModel;
- (void)dealloc
{
//    _tableView.delegate = nil;
//    _tableView.dataSource = nil;
    [_receiverKVO unobserveAll];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void) removeAllObserver
{
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
    [_receiverKVO unobserveAll];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype)initWith:(IMAUser *)user
{
    if (self = [super init])
    {
        _sendInputStatus = SendInputStatus_notSend;
        _receiver = user;
    }
    return self;
}

-(void)rightButtonClick
{
    if (!self.viewModel.info) {
        return;
    }
    
    if(_conversation.type == TIM_GROUP)
    {
        MHSettingCircleViewModel *viewModel = [[MHSettingCircleViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelUtilKey:self.viewModel.info}];
        [self.viewModel.services pushViewModel:viewModel animated:YES];
    }
   
}

- (void)addHeaderView
{
    self.headerView = [[ChatHeadRefreshView alloc] init];
}

-(void)bindViewModel
{
    [super bindViewModel];
    _sendInputStatus = SendInputStatus_notSend;
    _receiver = self.viewModel.user;
    
}







- (void)onRefresh
{

    __weak ChatViewController *ws = self;
    NSMutableArray *totalLoadList = [NSMutableArray array];
    
    [_conversation asyncLoadRecentMessage:kLoadDataPageSiez completion:^(NSArray *imamsgList, BOOL succ) {
        if (succ)
        {
            [totalLoadList addObjectsFromArray:imamsgList];
            [ws onLoadRecentMessage:imamsgList complete:YES scrollToBottom:YES];
            if (imamsgList.count < kLoadDataPageSiez) {
                [_conversation asyncLoadRecentMessage:kLoadDataPageSiez completion:^(NSArray *imamsgList, BOOL succ) {
                    if (succ)
                    {
                        [totalLoadList addObjectsFromArray:imamsgList];
                        [ws onLoadRecentMessage:[totalLoadList copy]  complete:YES scrollToBottom:YES];
                    }
                    [ws refreshCompleted];
                    [ws layoutHeaderRefreshView];
                }];
            }else
            {
                [ws onLoadRecentMessage:imamsgList complete:YES scrollToBottom:YES];
            }
        }
        
        
        
        [ws refreshCompleted];
        [ws layoutHeaderRefreshView];
    }];
    
    NSLog(@"2222");
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}




- (void)addFooterView
{
    // 作空实现
}

- (void)addOwnViews
{
    [super addOwnViews];
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = MH_MAIN_BACKGROUNDCOLOR_2;
    _tableView.sectionFooterHeight = 0.f;
    UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPress:)];
    longPressGr.minimumPressDuration = 1.0;
    [_tableView addGestureRecognizer:longPressGr];
}

-(void)onLongPress:(UILongPressGestureRecognizer *)gesture
{
//    [self hiddenKeyBoard:nil];
    if(gesture.state == UIGestureRecognizerStateBegan)
    {
        CGPoint point = [gesture locationInView:self.tableView];
        
        NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];
        UITableViewCell<TIMElemAbleCell> *cell = [_tableView cellForRowAtIndexPath:indexPath];
        BOOL showMenu = [cell canShowMenu];
        
        if (showMenu)
        {
            if ([cell canShowMenuOnTouchOf:gesture])
            {
                [cell showMenu];
//
            }
        }
    }
}




- (void)addChatToolBar
{
    CGFloat kToolbarY = CGRectGetMaxY(self.view.bounds) - CHAT_BAR_MIN_H - 2*CHAT_BAR_VECTICAL_PADDING;
    
    _toolbar = [[MyChatToolBarView alloc] initWithFrame:CGRectMake(0, kToolbarY, CGRectGetWidth(self.view.bounds), CHAT_BAR_MIN_H+2*CHAT_BAR_VECTICAL_PADDING) chatType:[_conversation type]];
    _toolbar.delegate = self;
    self.toolBar = _toolbar;
    [self.view addSubview:_toolbar];
//    self.view.backgroundColor = [UIColor redColor];
    [(MyMoreView *)_toolbar.moreView setDelegate:self];
//    self.refreshScrollView.backgroundColor = m;
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emotionDidSelect:) name:@"EmotionDidSelectNotification" object:nil];
    //键盘删除的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteBtn) name:@"EmotionDidDeleteNotification" object:nil];
    __weak __typeof(self)weakSelf = self;
    _toolBar.emojView.sendBlock = ^{
        [weakSelf sendText:weakSelf.toolBar.textInputView.text];
        weakSelf.toolBar.textInputView.text = @"";
    };
}



- (void)emotionDidSelect:(NSNotification *)notification
{
    XFEmotion *emotion = notification.userInfo[@"SelectEmotionKey"];
    [_toolbar.textInputView insertEmotion:emotion];
    //    _toolBar.textInputView.se
    
}

-(void)deleteBtn {
    [_toolbar.textInputView deleteBackward];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    [[NSNotificationCenter defaultCenter]removeObserver:self name:kIMAMSG_SendMsgNotification object:nil];
//    [self removeAllObserver];
//    if (!self.viewModel.info) {
//        return;
//    }
    self.view.backgroundColor = MH_MAIN_BACKGROUNDCOLOR_2;
    
    
    [self configWithUser:self.viewModel.user];
    [self addChatToolBar];
    __weak __typeof(self)weakSelf = self;
    if(_messageList.count <= 0)
    {
        [_conversation asyncLoadRecentMessage:kLoadDataPageSiez completion:^(NSArray *imamsgList, BOOL succ) {
            [weakSelf onLoadRecentMessage:imamsgList complete:succ scrollToBottom:YES];
        }];
    }else
    {
        [self scrollBottom];
    }
    
    @weakify(self);
    if(_conversation.type == TIM_GROUP)
    {
        [[[MHHTTPService sharedInstance] fetchCircleInfoWithCircleId:self.viewModel.circleId] subscribeNext:^(MHCircleInfo *info) {
            [AXAppDelegate sharedDelegate].currentCircleInfo = info;
            @strongify(self);
            self.viewModel.info = info;
            
            UIBarButtonItem *setting = [UIBarButtonItem mh_customItemWithTitle:@"" titleColor:nil imageName:@"ic_circle_setup" target:self selector:@selector(rightButtonClick) contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
            
            UIBarButtonItem *chatOwner = [UIBarButtonItem mh_customItemWithTitle:@"" titleColor:nil imageName:@"btn_circle_lqz" target:self selector:@selector(chatWithOwer) contentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
//            chatOwner.width = 30;
            self.navigationItem.rightBarButtonItems = [info currentUserIsOwner] ? @[setting] :  @[setting,chatOwner];
        }];
    }
   
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUpdateInputStatus:) name:kUserInputStatus object:nil];
    
    UITapGestureRecognizer* tapAction = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyBoard:)];
    [self.tableView addGestureRecognizer:tapAction];
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onRevokeMsg:) name:kIMAMSG_RevokeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeleteMsg:) name:kIMAMSG_DeleteNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResendMsg:) name:kIMAMSG_ResendNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChangedMsg:) name:kIMAMSG_ChangedNotification object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSendMsg:) name:kIMAMSG_SendMsgNotification object:nil];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem mh_customItemWithTitle:@"" titleColor:nil imageName:@"barbuttonicon_back_15x30" target:self selector:@selector(back) contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    
    if (_conversation.type == TIM_GROUP) {
        
       
    }
}


-(void) chatWithOwer
{
    if ([AXAppDelegate sharedDelegate].currentCircleInfo) {
        __weak __typeof(self)weakSelf = self;
        [[IMAPlatform sharedInstance] asyncGetStrangerInfo:[NSString stringWithFormat:@"%d",[AXAppDelegate sharedDelegate].currentCircleInfo.ownerUid] succ:^(IMAUser *auser) {
            MHChatViewModel *viewModel = [[MHChatViewModel alloc] initWithServices:weakSelf.viewModel.services params:@{MHViewModelUtilKey:auser}];
            viewModel.popToRoot = YES;
            [weakSelf.viewModel.services pushViewModel:viewModel animated:YES];
        } fail:^(int code, NSString *msg) {
            
        }];
    }
}

-(void) scrollBottom
{
    if (!self.viewModel.user) {
        return;
    }
    __weak __typeof(self)weakSelf = self;
 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//     if (self->_messageList.count > 0) {
//         return ;
//     }
     NSIndexPath *last = [NSIndexPath indexPathForRow:self->_messageList.count-1 inSection:0];
    [weakSelf.tableView scrollToRowAtIndexPath:last atScrollPosition:UITableViewScrollPositionBottom animated:NO];
//      weakSelf.tableView.contentInset = UIEdgeInsetsMake(0, 0,15,0);
});
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [self.navigationController.navigationBar setBackgroundImage:MHNavBackGround() forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = MH_MAIN_BACKGROUNDCOLOR_2;
//    [self configWithUser:self.viewModel.user];
    
}

-(void) onSendMsg:(NSNotification *)notify
{
    if ([notify.object isKindOfClass:[IMAMsg class]])
    {
        IMAMsg *msg = (IMAMsg *)notify.object;
        TIMOfflinePushInfo *info =  [TIMOfflinePushInfo new];
        info.desc = _conversation.type == TIM_GROUP ? @"" : @"主题消息";
        info.pushFlag =   _conversation.type == TIM_GROUP ? TIM_OFFLINE_PUSH_NO_PUSH :  TIM_OFFLINE_PUSH_DEFAULT ;
        [msg.msg setOfflinePushInfo:info];
        [self sendMsg:msg];
    }
}
- (void)onRevokeMsg:(NSNotification *)notify
{
    if ([notify.object isKindOfClass:[IMAMsg class]])//本地撤销
    {
        IMAMsg *msg = (IMAMsg *)notify.object;
        __weak typeof(self) ws = self;
        [_conversation revokeMsg:msg isRemote:NO completion:^(NSArray *imamsgList, BOOL succ, CommonVoidBlock removeingAction) {
            if (succ)
            {
                [ws onWillRefresh:imamsgList withAction:removeingAction];
            }
        }];
    }
    else if ([notify.object isKindOfClass:[TIMMessageLocator class]])//接收到撤销消息
    {
        IMAMsg *msg = [self findMsg:(TIMMessageLocator *)notify.object];
        if (!msg) {
            return;
        }
        __weak typeof(self) ws = self;
        [_conversation revokeMsg:msg isRemote:YES completion:^(NSArray *imamsgList, BOOL succ, CommonVoidBlock removeingAction) {
            if (succ)
            {
                [ws onWillRefresh:imamsgList withAction:removeingAction];
            }
        }];
    }
//    [self.toolBar updateButtomView:nil];
}

- (IMAMsg *)findMsg:(TIMMessageLocator *)locator
{
    for (IMAMsg *imaMsg in _messageList.safeArray)
    {
        if ([imaMsg.msg respondsToLocator:locator])
        {
            return imaMsg;
        }
    }
    return nil;
}

- (void)onDeleteMsg:(NSNotification *)notify
{
    IMAMsg *msg = (IMAMsg *)notify.object;
//    __weak __typeof(self)weakSelf = self;
    __weak __typeof(self)weakSelf = self;
    [_conversation removeMsg:msg completion:^(NSArray *imamsgList, BOOL succ, CommonVoidBlock removingAction) {
        if (succ)
        {
            [weakSelf onWillRemove:imamsgList withAction:removingAction];
        }
    }];
//    [self.toolBar updateButtomView:nil];
}

- (void)onResendMsg:(NSNotification *)notify
{
    IMAMsg *msg = (IMAMsg *)notify.object;
    __weak __typeof(self)weakSelf = self;
    [_conversation removeMsg:msg completion:^(NSArray *imamsgList, BOOL succ, CommonVoidBlock removingAction) {
        if (succ)
        {
            [weakSelf onWillRemove:imamsgList withAction:removingAction];
        }
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf sendMsg:msg];
    });
    
}


//处理
-(void)back
{
    if (_conversation.lastMessage.msg) {
         [[AXAppDelegate sharedDelegate].imGroupImMessageUpdate setObject:_conversation.lastMessage.msg.msgId forKey:self.viewModel.user.userId];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kIMAMSG_SendMsgNotification object:nil];
    [[[IMAPlatform sharedInstance].conversationMgr conversationList] removeAllObjects];
    
    [[IMAPlatform sharedInstance].conversationMgr asyncConversationList];
    
    //退出时上报一次已读，以前是没收到一条消息都上报，会导致server接收到大量的已读上报消息
    [_conversation setReadAllMsg];
    
    NSArray * controllers = [self.navigationController viewControllers];
    for (int i = 0; i < [controllers count]; i++){
        
        UIViewController * controllerTest = [controllers objectAtIndex:i];
        
        if(self.viewModel.popToRoot || [controllerTest isKindOfClass:[MHSettingCirleInfoViewController class]] || ([_conversation type] == TIM_C2C && [controllerTest isKindOfClass:[MHCircleMemberViewController class]]  )){
            [self.viewModel.services popToRootViewModelAnimated:YES];
            break;
        }
        
    }
    [super back];
    [_receiverKVO unobserveAll];
}

- (void)onWillRefresh:(NSArray *)imamsgList withAction:(CommonVoidBlock)action
{
    [UIView setAnimationsEnabled:NO];
    [_tableView beginUpdates];
    
    NSMutableArray *indexArray = [NSMutableArray array];
    
    for (IMAMsg *removemsg in imamsgList)
    {
        NSInteger idx = [_messageList indexOfObject:removemsg];
        NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
        [indexArray addObject:index];
    }
    [_tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationNone];
    [_tableView endUpdates];
    [UIView setAnimationsEnabled:YES];
}

- (void)onWillRemove:(NSArray *)imamsgList withAction:(CommonVoidBlock)action
{
    [_tableView beginUpdates];
    
    NSMutableArray *indexArray = [NSMutableArray array];
    
    for (IMAMsg *removemsg in imamsgList)
    {
        NSInteger idx = [_messageList indexOfObject:removemsg];
        NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
        [indexArray addObject:index];
    }
    
    if (action)
    {
        action();
    }
    
    [_tableView deleteRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationNone];
    
    [_tableView endUpdates];
}

- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput cancelSendMsg:(IMAMsg *)msg
{
    if (msg)
    {
        __weak __typeof(self)weakSelf = self;
        [_conversation removeMsg:msg completion:^(NSArray *imamsgList, BOOL succ, CommonVoidBlock removingAction) {
            if (succ)
            {
                [weakSelf onWillRemove:imamsgList withAction:removingAction];
            }
        }];
        
    }
}


//- (void)onChatInputSendImage:(UIView<ChatInputAbleView> *)chatInput
//{
//    [self moreViewPhotoAction];
//}
//- (void)onChatInputTakePhoto:(UIView<ChatInputAbleView> *)chatInput
//{
//    [self moreViewCameraAction];
//}
//- (void)onChatInputSendFile:(UIView<ChatInputAbleView> *)chatInput
//{
//    [self moreViewFileAction];
//}
//- (void)onChatInputRecordVideo:(UIView<ChatInputAbleView> *)chatInput
//{
//    [self moreVideVideoAction];
//}


- (void)onChangedMsg:(NSNotification *)notify
{
    IMAMsg *msg = (IMAMsg *)notify.object;
    
    NSInteger idx = [_conversation.msgList indexOfObject:msg];
    if (idx >= 0 && idx < _conversation.msgList.count)
    {
        [_tableView beginUpdates];
        NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
        [_tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
        [_tableView endUpdates];
    }
}


- (void)configWithUser:(IMAUser *)user
{
    [_receiverKVO unobserveAll];
    _receiver = self.viewModel.user;
    //    _receiver = user;
    __weak ChatViewController *ws = self;
    
    _receiverKVO = [FBKVOController controllerWithObserver:self];
    
    [_receiverKVO observe:_receiver keyPaths:@[@"remark", @"nickName"] options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
        [ws setChatTitle];
    }];
//
    if (_conversation)
    {
        [_conversation releaseConversation];
        _messageList = nil;
//        _conversation.
        [self reloadData];
    }
    
    
    
    _conversation = [[IMAPlatform sharedInstance].conversationMgr chatWith:user];
    _conversation.perLoadLastMessage = nil;
    _messageList = _conversation.msgList;
    
    __weak __typeof(self)weakSelf = self;
    _conversation.receiveMsg = ^(NSArray *imamsgList, BOOL succ) {
        [weakSelf modifySendInputStatus:SendInputStatus_Send];
        [weakSelf onReceiveNewMsg:imamsgList succ:succ];
        [weakSelf updateMessageList];
    };
    
    
    
    [self addChatSettingItem];
    
    
    [self setChatTitle];
    
    // 同步群资料
    //    if ([user isGroupType])
    //    {
    //        [((IMAGroup *)user) asyncUpdateGroupInfo:nil fail:nil];
    //    }
}

- (void)setChatTitle
{
    NSString *title = [_receiver showTitle];
    if (title.length > 10)
    {
        title = [NSString stringWithFormat:@"%@...", [title substringToIndex:10]];
    }
    self.title = title;
}

- (void)onReceiveNewMsg:(NSArray *)imamsgList succ:(BOOL)succ
{
//    [_tableView beginUpdates];
//
//    NSInteger count = [imamsgList count];
//    NSMutableArray *indexArray = [NSMutableArray array];
//    for (NSInteger i = 0; i < count; i++)
//    {
//        NSInteger idx = _messageList.count + i - count;
//        NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
//        [indexArray addObject:index];
//    }
//
//    [_tableView insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationBottom];
//    [_tableView endUpdates];
//
//
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self updateOnSendMessage:imamsgList succ:YES];
//    });
    
    [UIView setAnimationsEnabled:NO];
    [_tableView beginUpdates];
    NSInteger count = [imamsgList count];
    NSMutableArray *indexArray = [NSMutableArray array];
    for (NSInteger i = 0; i < count; i++)
    {
        NSInteger idx = _messageList.count + i - count;
        NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
        [indexArray addObject:index];
    }
    [_tableView insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationNone];
    [_tableView endUpdates];
    [UIView setAnimationsEnabled:YES];
    [self updateOnSendMessage:imamsgList succ:YES];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self updateOnSendMessage:imamsgList succ:YES];
//    });
}

//当消息量过大时，需要清理部分消息，避免内存持续增长
- (void)updateMessageList
{
    if (_messageList.count > 1000)
    {
        DebugLog(@"_messageList.count > 1000");
        int rangLength = 100;
        NSRange range = NSMakeRange(_messageList.count-rangLength, rangLength);
        [_messageList subArrayWithRange:range];
        [_tableView reloadData];
    }
}

- (void)onLoadRecentMessage:(NSArray *)imamsgList complete:(BOOL)succ scrollToBottom:(BOOL)scroll
{
    if (succ)
    {
        if (imamsgList.count > 0)
        {
//            [UIView setAnimationsEnabled:NO];
//            [_tableView beginUpdates];
//
//            NSMutableArray *ar = [NSMutableArray array];
//            for (NSInteger i = 0; i < imamsgList.count; i++)
//            {
//                [ar addObject:[NSIndexPath indexPathForItem:i inSection:0]];
//            }
//
//            [_tableView insertRowsAtIndexPaths:ar withRowAnimation:UITableViewRowAnimationTop];
//
//            [_tableView endUpdates];
//            [UIView setAnimationsEnabled:YES];
//            if (scroll)
//            {
//                NSIndexPath *last = [NSIndexPath indexPathForRow:imamsgList.count-1 inSection:0];
//                [self.tableView scrollToRowAtIndexPath:last atScrollPosition:UITableViewScrollPositionBottom animated:YES];
//            }
            
            NSInteger preCount = _messageList.count - imamsgList.count;
//            NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,[imamsgList count])];
//            [_messageList insertObjects:imamsgList atIndexes:indexes];
            [self.tableView reloadData];
            NSInteger curCount = _messageList.count;
            if(preCount == 0 || (curCount - preCount)<=0) {
                [self scrollBottom];
            }else {
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:curCount - preCount inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
            }
        }
    }

}

- (void)layoutRefreshScrollView
{
    CGFloat kToolbarY = CGRectGetMaxY(self.view.bounds) - CHAT_BAR_MIN_H - 2*CHAT_BAR_VECTICAL_PADDING;
    // do nothing
    _tableView.frame = CGRectMake(CGRectGetMinX(self.view.bounds), CGRectGetMinY(self.view.bounds), CGRectGetWidth(self.view.bounds), kToolbarY - 10);
    _toolbar.frame = CGRectMake(0, kToolbarY, CGRectGetWidth(self.view.bounds), CHAT_BAR_MIN_H+2*CHAT_BAR_VECTICAL_PADDING);
//    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 10,0); //高度
}


- (void)addChatSettingItem
{
    DebugLog(@"子类实现");
}

- (void)onClickChatSetting
{
    DebugLog(@"在子类中实现");
}

// 加载历史信息
- (void)loadHistotyMessages
{
    
}

// 添加收到的信息
- (void)appendReceiveMessage
{
    
}

///==========================
#pragma mark - MyChatToolBarViewDelegate

- (void)updateOnSendMessage:(NSArray *)msglist succ:(BOOL)succ
{
    if (msglist.count)
    {
        NSInteger index = [_messageList indexOfObject:msglist.lastObject];
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

- (void)sendMsg:(IMAMsg *)msg
{
    if (msg)
    {
        //        _isSendMsg = YES;
        [UIView setAnimationsEnabled:NO];
        [_tableView beginUpdates];
        
        __weak ChatViewController *ws = self;
        DebugLog(@"will sendmessage");
        
        NSArray *newaddMsgs = [_conversation sendMessage:msg completion:^(NSArray *imamsglist, BOOL succ, int code) {
            
            DebugLog(@"sendmessage end");
          
              [ws updateOnSendMessage:imamsglist succ:succ];
            if (!succ)
            {
                if (code == kSaftyWordsCode)
                {
                    IMAMsg *msg = [IMAMsg msgWithCustom:EIMAMSG_SaftyTip param:@"安全文本打击"];
                    [self->_messageList addObject:msg];
                    
                    [ws showMsgs:@[msg]];
                }
            }
        }];
    
        
        [self showMsgs:newaddMsgs];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    // 开始拖拽滑动时，收起键盘
     [self.toolBar endEditing:YES];
}
//-(void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    [super scrollViewDidScroll:scrollView];
//    if (self.toolBar.textInputView.isFirstResponder) {
//        [self.toolBar endEditing:YES];
//    }
//
//
//}

- (void)showMsgs:(NSArray *)msgs
{
    NSMutableArray *array = [NSMutableArray array];
    
    for (IMAMsg *msg in msgs)
    {
        NSInteger idx = [_messageList indexOfObject:msg];
        NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
        [array addObject:index];
    }
    
//    for (IMAMsg *msg in msgs)
//    {
//        NSInteger idx = [msgs indexOfObject:msg]; // 0 1 2 //
//
//        NSIndexPath *index = [NSIndexPath indexPathForRow:_messageList.count - msgs.count-1 + idx inSection:0];
//        [array addObject:index];
//    }
    
//    NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(_messageList.count - msgs.count,msgs.count)];
//    [self.data insertObjects:tempArray atIndexes:indexes];
    
    [_tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationNone];
    [_tableView endUpdates];
    [UIView setAnimationsEnabled:YES];
    [self scrollBottom];
}

- (void)modifySendInputStatus:(SendInputStatus)status
{
    _sendInputStatus = status;
}

- (void)onUpdateInputStatus:(NSNotification *)notify
{
    CustomElemCmd *elem = (CustomElemCmd *)notify.object;
    if ([elem.actionParam isEqualToString:@"EIMAMSG_InputStatus_Ing"])
    {
        DebugLog(@"EIMAMSG_InputStatus_Ing");
        self.title = @"对方正在输入...";
        
        if (!_inputStatusTimer)
        {
            _inputStatusTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(onRestoreTitle:) userInfo:nil repeats:YES];
        }
    }
    else if ([elem.actionParam isEqualToString:@"EIMAMSG_InputStatus_End"])
    {
        DebugLog(@"EIMAMSG_InputStatus_End");
        [self onRestoreTitle:nil];
    }
}

- (void)onRestoreTitle:(NSTimer *)timer
{
    if (_inputStatusTimer)
    {
        [_inputStatusTimer invalidate];
        _inputStatusTimer = nil;
    }
    
    [self setChatTitle];
}

- (void)sendInputStatus
{
    DebugLog(@"chatviewcontroller sendInputStatus");
    if (_sendInputStatus == SendInputStatus_Send && ![_receiver isGroupType])
    {
        IMAMsg *msg = [IMAMsg msgWithCustom:EIMAMSG_InputStatus param:@"EIMAMSG_InputStatus_Ing"];
        [_conversation sendOnlineMessage:msg.msg succ:nil fail:^(int code, NSString *msg) {
            
            DebugLog(@"send online msg fail,code = %d,fail = %@", code, msg);
        }];
    }
}

- (void)sendStopInputStatus
{
    if (_sendInputStatus == SendInputStatus_Send && ![_receiver isGroupType])
    {
        IMAMsg *msg = [IMAMsg msgWithCustom:EIMAMSG_InputStatus param:@"EIMAMSG_InputStatus_End"];
        [_conversation sendOnlineMessage:msg.msg succ:nil fail:^(int code, NSString *msg) {
            
            DebugLog(@"send stop online msg fail,code = %d,fail = %@", code, msg);
        }];
    }
}

- (void)sendText:(NSString *)text
{
    if (text && text.length > 0)
    {
        IMAMsg *msg = [IMAMsg msgWithText:text];
        TIMOfflinePushInfo *info =  [TIMOfflinePushInfo new];
        info.desc = _conversation.type == TIM_GROUP ? @"" : text;
        info.pushFlag =   _conversation.type == TIM_GROUP ? TIM_OFFLINE_PUSH_NO_PUSH :  TIM_OFFLINE_PUSH_DEFAULT ;
        [msg.msg setOfflinePushInfo:info];

        [self sendMsg:msg];
    }
}
- (void)didChangeToolBarHight:(CGFloat)toHeight
{
    __weak ChatViewController* weakself = self;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = weakself.tableView.frame;
        rect.origin.y = 0;
        rect.size.height = weakself.view.frame.size.height - toHeight - 10;
        weakself.tableView.frame = rect;
        [weakself.toolBar updateEmoj];
    }];
    
    
    if (_tableView.contentSize.height > _tableView.frame.size.height)
    {
        CGPoint offset = CGPointMake(0, _tableView.contentSize.height - _tableView.frame.size.height);
        [_tableView setContentOffset:offset animated:YES];
    }
}
- (void)sendAudioRecord:(AudioRecord *)audio
{
    IMAMsg *msg = [IMAMsg msgWithSound:audio.audioData duration:audio.duration];
    [self sendMsg:msg];
}


//- (void)sendInputStatus;
//
//- (void)sendStopInputStatus;
//
//- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput sendMsg:(IMAMsg *)msg;
//
//// 效果参考ios微信发语间消息效果
//// 即将发送msg
//- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput willSendMsg:(IMAMsg *)msg;
//
//// 使用新消息替换原来的
//- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput replaceWith:(IMAMsg *)newMsg oldMsg:(IMAMsg *)msg;
//
//// 取消即将发送的
//- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput cancelSendMsg:(IMAMsg *)msg;

//===========================

- (UIImagePickerController *)imagePicker
{
    if (_imagePicker == nil)
    {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

- (void)sendImage:(UIImage *)image orignal:(BOOL)orignal
{
    if (image)
    {
        IMAMsg *msg = [IMAMsg msgWithImage:image isOrignal:orignal];
        TIMOfflinePushInfo *info =  [TIMOfflinePushInfo new];
        info.desc = _conversation.type == TIM_GROUP ? @"" : @"[图片]";
        info.pushFlag =   _conversation.type == TIM_GROUP ? TIM_OFFLINE_PUSH_NO_PUSH :  TIM_OFFLINE_PUSH_DEFAULT ;
        [msg.msg setOfflinePushInfo:info];
        [self sendMsg:msg];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
    {
        UIImage *image = [info[UIImagePickerControllerOriginalImage] fixOrientation];
        NSData *data = UIImagePNGRepresentation(image);
        
        if(data.length > 28 * 1024 * 1024)
        {
            [[HUDHelper sharedInstance] tipMessage:@"发送的文件过大"];
            return;
        }
        
        ImageThumbPickerViewController *vc = [[ImageThumbPickerViewController alloc] initWith:image];
        __weak ChatViewController *ws = self;
        vc.sendImageBlock = ^ (ImageThumbPickerViewController *svc, BOOL isOrignal) {
            [ws sendImage:svc.showImage orignal:isOrignal];
            ws.imagePicker = nil;
            
        };
        [picker pushViewController:vc animated:YES];
    }
    else if([mediaType isEqualToString:(NSString*)kUTTypeMovie])
    {
        [picker dismissViewControllerAnimated:YES completion:nil];
        if (self.imagePicker.mediaTypes.count == 2)
        {
            //将文件转换为data
            NSURL *url = info[UIImagePickerControllerMediaURL];
            NSError *err = nil;
            NSData* data = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&err];
            
            //将data保存到cache目录
            NSTimeInterval curTime = [NSDate timeIntervalSinceReferenceDate];
            NSString *extName = [[url absoluteString] pathExtension];
            NSString *cachePath = [PathUtility getCachePath];
            NSString *saveToDir = [NSString stringWithFormat:@"%@/timchat/",cachePath];
            NSString *saveFileName = [NSString stringWithFormat:@"sendVideo_%d.%@",(int)curTime,extName];
            
            //判断目录是否存在
            BOOL isDir = FALSE;
            BOOL isDirExist = [[NSFileManager defaultManager] fileExistsAtPath:saveToDir isDirectory:&isDir];
            if (!(isDir && isDirExist))
            {
                BOOL isCreateDir = [PathUtility createDirectoryAtCache:@"timchat"];
                if (!isCreateDir) {
                    return;
                }
            }
            
            //判断文件是否存在
            NSString *filePath = [NSString stringWithFormat:@"%@%@",saveToDir,saveFileName];
            if (![PathUtility isExistFileInDocument:saveFileName])
            {
                BOOL isCreate = [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
                if (!isCreate)
                {
                    return ;
                }
            }
            NSError *error = nil;
            [data writeToFile:filePath options:NSDataWritingAtomic error:&error];
            if (error) {
                [HUDHelper alert:@"保存视频失败"];
                return;
            }
            if(data.length < 28 * 1024 * 1024)
            {
                //文件最大不超过28MB
                NSURL *saceUrl = [NSURL URLWithString:filePath];
                IMAMsg *msg = [IMAMsg msgWithFilePath:saceUrl];
                [self sendMsg:msg];
            }
            else
            {
                [[HUDHelper sharedInstance] tipMessage:@"发送的文件过大"];
            }
        }
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
    _imagePicker = nil;
}

#pragma mark - moreView
-(void)hiddenKeyBoard:(UITapGestureRecognizer *) tap
{
    if ([_toolBar.textInputView isFirstResponder] || !tap) {
         [_toolbar endEditing:YES];
    }else if(self.toolBar.moreBtn.selected)
    {
        [self.toolBar btnAction:self.toolBar.moreBtn];
    }else if(self.toolBar.emojBtn.selected)
    {
//        [self.toolBar.emojBtn setImage:[UIImage imageNamed:@"chat_toolbar_smile_nor"] forState:UIControlStateNormal];
        self.toolBar.emojBtn.selected = NO;
        [self.toolBar updateButtomView:nil];
//        [self.toolBar btnAction:self.toolBar.emojBtn];
    }else
    {
        CGPoint location = [tap locationInView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
        ChatCustomVideoImageCell *customeCell  = [self.tableView cellForRowAtIndexPath: indexPath];
    
        if (_conversation.type == TIM_GROUP && indexPath && [customeCell isKindOfClass:[ChatCustomVideoImageCell class]]) {
    
            CGPoint touchPoint = [tap locationInView:customeCell.containerView];
            if (CGRectContainsPoint(customeCell.containerView.frame, touchPoint)) {
                IMAMsg *msg = [_messageList objectAtIndex:indexPath.row];
                MHMoment *moment =  [self momentWithMsg:msg];
                if (moment) {
                    if (moment.videoInfo) {
                        MHAwemeListViewModel *viewModel = [[MHAwemeListViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelUtilKey:@[],MHViewModelCommonModelUtilKey:moment,@"MHViewModelHiddenEnter":@(YES),@"MHViewModelShowEnterBtn":@false}];
                        [self.viewModel.services pushViewModel:viewModel animated:YES];
                    }else
                    {
                        MHMomentDetailViewModel *detail = [[MHMomentDetailViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelIDKey:@(moment.autoId),MHViewModelIsDetail:@(true)}];
                        [self.viewModel.services pushViewModel:detail animated:YES];
                    }
                }
            }
            
          
        }
    }
   
    
    //    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

#pragma mark - MyMoreViewDelegate
- (void)moreViewPhotoAction
{
    
    if (_conversation.type == TIM_GROUP) {
        
//        [[[MHHTTPService sharedInstance] fetchCircleInfoWithCircleId:self.viewModel.circleId] subscribeNext:^(MHCircleInfo *info) {
             
//            self.viewModel.info = info;
        
        if (!self.viewModel.info) {
            return;
        }
        
        if ([AXAppDelegate sharedDelegate].currentCircleInfo.canPublish) {
            __weak __typeof(self)weakSelf = self;
            [self openCameraIsPublish:YES selectedAssets:nil completionBlock:^(NSArray *photos,NSArray *assert){
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                [dic setObject:weakSelf.viewModel.info forKey:MHViewModelUtilKey];
                if (photos) {
                    [dic setObject:photos forKey:@"MHViewModelPhotoes"];
                }
                
                if (assert) {
                    [dic setObject:assert forKey:@"MHViewModelAsserts"];
                }
                MHComposeViewModel *viewModel = [[MHComposeViewModel alloc] initWithServices:self.viewModel.services
                                                                                      params:[dic copy]];
                
                [weakSelf.viewModel.services presentViewModel:viewModel animated:YES completion:nil];
            }];
            
        }else
        {
            [MBProgressHUD mh_showTips:@"没有发表权限"];
        }
//        }];
        
    }else
    {
        // 隐藏键盘
        [self hiddenKeyBoard:nil];
        
        if(self)
            // 弹出照片选择
            self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        [self presentViewController:self.imagePicker animated:YES completion:NULL];
    }
    
}
- (void)moreViewCameraAction
{
    
    if (_conversation.type == TIM_GROUP) {
        if (!self.viewModel.info) {
            return;
        }
//        [[[MHHTTPService sharedInstance] fetchCircleInfoWithCircleId:self.viewModel.circleId] subscribeNext:^(MHCircleInfo *info) {
            [AXAppDelegate sharedDelegate].currentCircleInfo = self.viewModel.info;
//            self.viewModel.info = info;
            if ([AXAppDelegate sharedDelegate].inUploading) {
                [MBProgressHUD mh_showTips:@"视频正在上传中，请稍后再试..."];
            }else
            {
                MHVideoRecordViewModel *viewModel = [[MHVideoRecordViewModel alloc] initWithServices:self.viewModel.services
                                                                                              params:nil];
                [self.viewModel.services presentViewModel:viewModel animated:YES completion:nil];
            }
//        }];
    }else
    {
         [self hiddenKeyBoard:nil];
        
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        [self.imagePicker setEditing:YES];
        if ([[AVCaptureDevice class] respondsToSelector:@selector(authorizationStatusForMediaType:)])
        {
            AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authorizationStatus == AVAuthorizationStatusRestricted || authorizationStatus == AVAuthorizationStatusDenied)
            {
                // 没有权限
                [HUDHelper alertTitle:@"提示" message:@"请在设备的\"设置-隐私-相机\"中允许访问相机。" cancel:@"确定"];
                return;
            }
        }
        [self presentViewController:self.imagePicker animated:YES completion:NULL];
    }
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self hiddenKeyBoard:nil];
    [_conversation setReadAllMsg];
    [[ChatSoundPlayer sharedInstance] stopPlay];
//    [MHNotificationCenter postNotificationName:MHReloadFirstPageDataNotification object:nil];
}

- (void)moreViewFileAction
{
    // 隐藏键盘，只能选择图片或视频文件
    [self hiddenKeyBoard:nil];
    if (!self.viewModel.info) {
        return;
    }
    
//    [[[MHHTTPService sharedInstance] fetchCircleInfoWithCircleId:self.viewModel.circleId] subscribeNext:^(MHCircleInfo *info) {
        [AXAppDelegate sharedDelegate].currentCircleInfo = self.viewModel.info;
//        self.viewModel.info = info;
        MHAskViewModel *viewModel = [[MHAskViewModel alloc] initWithServices:self.viewModel.services
                                                                      params:@{MHViewModelUtilKey:self.viewModel.info}];
        viewModel.info = self.viewModel.info;
        [self.viewModel.services pushViewModel:viewModel animated:YES];
//    }];
    
    
    
//    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];
//    [self presentViewController:self.imagePicker animated:YES completion:NULL];
}

-(void) moreViewImageThemeAction
{
     [self hiddenKeyBoard:nil];
    if (!self.viewModel.info) {
        return;
    }
    if ([AXAppDelegate sharedDelegate].currentCircleInfo.canPublish) {
        
        
        __weak __typeof(self)weakSelf = self;
        [self openCameraIsPublish:YES selectedAssets:nil completionBlock:^(NSArray *photos,NSArray *assert){
            //                        NSArray *photos = photosDic[@"photos"];
            //                        NSArray *asserts = photosDic[@"assert"];
            //底部弹出
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:weakSelf.viewModel.info forKey:MHViewModelUtilKey];
            if (photos) {
                [dic setObject:photos forKey:@"MHViewModelPhotoes"];
            }
            
            if (assert) {
                [dic setObject:assert forKey:@"MHViewModelAsserts"];
            }
            MHComposeViewModel *viewModel = [[MHComposeViewModel alloc] initWithServices:self.viewModel.services
                                                                                  params:[dic copy]];
            
            [weakSelf.viewModel.services presentViewModel:viewModel animated:YES completion:nil];
        }];
        
    }else
    {
        [MBProgressHUD mh_showTips:@"没有发表权限"];
    }
    //}
    //    if (index == 0) {
    //        [[AXAppDelegate sharedDelegate] clearPublishDatas];
    //        [TXUGCBase setLicenceURL:@"http://license.vod2.myqcloud.com/license/v1/42003ce1c142554c34c267d6887d3437/TXUgcSDK.licence" key:@"9e00381d6a084de6980fae22a259b196"];
    //        [weakSelf.viewModel.bottomInfoViewModel.takeVideoCommand execute:nil];
    //    }else if (index == 1)
    //    {
    //        if ([AXAppDelegate sharedDelegate].currentCircleInfo.canPublish) {
    //            [self openCameraIsPublish:YES selectedAssets:nil completionBlock:^(NSArray *photos,NSArray *assert){
    //                [weakSelf.viewModel.bottomInfoViewModel.pulishCommand execute:@{@"photos":photos,@"assert":assert}];
    //            }];
    //
    //        }else
    //        {
    //            [MBProgressHUD mh_showTips:@"没有发表权限"];
    //        }
    //    }else
    //    {
    //        [weakSelf.viewModel.bottomInfoViewModel.askCommand execute:nil];
    //
    //    }
}




- (void)moreVideVideoAction
{
    // 隐藏键盘
     [self hiddenKeyBoard:nil];
    
    if ([[AVCaptureDevice class] respondsToSelector:@selector(authorizationStatusForMediaType:)])
    {
        AVAuthorizationStatus videoStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (videoStatus == 	AVAuthorizationStatusRestricted || videoStatus == AVAuthorizationStatusDenied)
        {
            // 没有权限
            [HUDHelper alertTitle:@"提示" message:@"请在设备的\"设置-隐私-相机\"中允许访问相机。" cancel:@"确定"];
            return;
        }
        
        AVAuthorizationStatus audioStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (audioStatus == 	AVAuthorizationStatusRestricted || audioStatus == AVAuthorizationStatusDenied)
        {
            // 没有权限
            [HUDHelper alertTitle:@"提示" message:@"请在设备的\"设置-隐私-麦克风\"中允许访问麦克风。" cancel:@"确定"];
            return;
        }
        __weak ChatViewController *ws = self;
        if (videoStatus == AVAuthorizationStatusNotDetermined)
        {
            //请求相机权限
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted){
                
                
                if(granted)
                {
                    AVAuthorizationStatus audio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
                    if (audio == AVAuthorizationStatusNotDetermined)
                    {
                        //请求麦克风权限
                        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted){
                            dispatch_async(dispatch_get_main_queue(), ^{
                                if (granted)
                                {
                                    [ws addMicroVideoView];
                                }
                            });
                        }];
                    }
                    else//这里一定是有麦克风权限了
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [ws addMicroVideoView];
                        });
                    }
                }
                
            }];
        }
        else//这里一定是有相机权限了
        {
            if (audioStatus == AVAuthorizationStatusNotDetermined)
            {
                //请求麦克风权限
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted){
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (granted)
                        {
                            [ws addMicroVideoView];
                        }
                    });
                    
                }];
            }
            else//这里一定是有麦克风权限了
            {
                [ws addMicroVideoView];
            }
            
        }
    }
}

- (void)addMicroVideoView
{
    //    CGFloat selfWidth  = self.view.bounds.size.width;
    //    CGFloat selfHeight = self.view.bounds.size.height;
    //    MicroVideoView *microVideoView = [[MicroVideoView alloc] initWithFrame:CGRectMake(0, selfHeight/3, selfWidth, selfHeight * 2/3)];
    //    microVideoView.delegate = self;
    //    [self.view addSubview:microVideoView];
    
    //    TCVideoRecordViewController *videoRecordVC = [[TCVideoRecordViewController alloc] init];
    //    TCNavigationController *nav = [[TCNavigationController alloc] initWithRootViewController:videoRecordVC];
    //    videoRecordVC.delegate = self;
    //    [self presentViewController:nav animated:YES completion:nil];
}

- (void)recordVideoPath:(NSString *)path
{
    NSError *err = nil;
//    self.edgesForExtendedLayout
    NSData* data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:path] options:NSDataReadingMappedIfSafe error:&err];
    //文件最大不超过28MB
    if(data.length < 28 * 1024 * 1024)
    {
        IMAMsg *msg = [IMAMsg msgWithVideoPath:path];
        [self sendMsg:msg];
    }
    else
    {
        [[HUDHelper sharedInstance] tipMessage:@"发送的文件过大"];
    }
}

- (void)touchUpDone:(NSString *)savePath
{
    NSError *err = nil;
    NSData* data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:savePath] options:NSDataReadingMappedIfSafe error:&err];
    //文件最大不超过28MB
    if(data.length < 28 * 1024 * 1024)
    {
        IMAMsg *msg = [IMAMsg msgWithVideoPath:savePath];
        [self sendMsg:msg];
    }
    else
    {
        [[HUDHelper sharedInstance] tipMessage:@"发送的文件过大"];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    IMAMsg *msg = [_messageList objectAtIndex:indexPath.row];
    IMAGroupMember *groupInfo = [msg getSender];
    if([msg type]== EIMAMSG_TimeTip && _messageList.count > indexPath.row + 1)
    {
        IMAMsg *nextMsg = [_messageList objectAtIndex:indexPath.row + 1];
        IMAGroupMember *nextGroupInfo = [nextMsg getSender];
        if([nextGroupInfo isKindOfClass:[IMAGroupMember class]] && [nextGroupInfo.memberInfo.member isEqualToString:MH_IM_MANAGERIDENTIFY] )
        {
            return 0;
        }
    }
    
    if([groupInfo isKindOfClass:[IMAGroupMember class]] && [groupInfo.memberInfo.member isEqualToString:MH_IM_MANAGERIDENTIFY] )
    {
        CustomElemCmd *elemCmd = [[IMAPlatform sharedInstance].conversationMgr  isOnlineMsg:[msg.msg getElem:0]];
        MHIMMessageType type  =  [[elemCmd.customInfo objectForKey:@"msgType"] intValue];
        if (type == MHIMMessageTypeRedPacketMessaege || type == MHIMMessageTypeTotalRedPacketMessage || type == MHIMMessageTypeJoinCircleName) {
            return [msg heightInWidth:tableView.bounds.size.width inStyle:_conversation.type == TIM_GROUP];
        }else
        {
            return 0;
        }
    }else
    {
        return [msg heightInWidth:tableView.bounds.size.width inStyle:_conversation.type == TIM_GROUP];
    }
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MHChatGroupHeaderView *headerView = [MHChatGroupHeaderView mh_viewFromXib];
    
     [RACObserve([AXAppDelegate sharedDelegate], uploadProgress) subscribeNext:^(NSNumber *num) {
         headerView.progressBar.progress = [num floatValue];
     }];
    [[[MHHTTPService sharedInstance] getChatCircleSimpleInfoWithCircleId:self.viewModel.circleId] subscribeNext:^(MHCircleSimpleInfo *info) {
       int count = info.recentImgList.count;
        headerView.thirdImageView.hidden = (count == 0);
        headerView.maskView.hidden =  (count == 0);
        headerView.seconImaegView.hidden = (count <= 1);
        headerView.firstImageView.hidden = (count <= 2);
        headerView.countLabel.text = [NSString stringWithFormat:@"%d\n条动态",info.recentCount];
        headerView.countLabel.numberOfLines = 2;
        for (MHRecentImgList *imageList in info.recentImgList) {
           int index = [info.recentImgList indexOfObject:imageList];
            if (index == 0) {
                [headerView.thirdImageView yy_setImageWithURL:[NSURL URLWithString:imageList.coverUrl] placeholder:MHDefaultAvatar(MHDefaultAvatarTypeDefualt)];
            }else if (index == 1)
            {
                [headerView.seconImaegView yy_setImageWithURL:[NSURL URLWithString:imageList.coverUrl] placeholder:MHDefaultAvatar(MHDefaultAvatarTypeDefualt)];
            }else if (index == 2)
            {
                [headerView.firstImageView yy_setImageWithURL:[NSURL URLWithString:imageList.coverUrl] placeholder:MHDefaultAvatar(MHDefaultAvatarTypeDefualt)];
            }
        }
        self.title = [NSString stringWithFormat:@"%@(%d人)",self.viewModel.title,info.memberCount];
    }];
    __weak __typeof(self)weakSelf = self;
    [headerView bk_whenTapped:^{
        
        
        MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:weakSelf.viewModel.services params:@{MHViewModelIDKey:@(weakSelf.viewModel.circleId)}];
        [weakSelf.viewModel.services pushViewModel:viewModel animated:YES];
    }];
    
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return _conversation.type == TIM_GROUP ? 51 : 0 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_messageList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSInteger testIndex = 0;
    
    DebugLog(@"-------------->_messageList.count = %ld", (long)_messageList .count);
    
    NSString *font = [NSString stringWithFormat:@"-------------->cellForRowAtIndexPath crash font(%ld)", (long)testIndex];
    DebugLog(@"%@", font);
    
    NSLog(@"indexPath.row == %lu",indexPath.row);
    
    IMAMsg *msg = [_messageList objectAtIndex:indexPath.row];
    
    msg.senderUser = self.viewModel.user;
    //    msg.msg.getSenderProfile
    NSString *rail = [NSString stringWithFormat:@"-------------->cellForRowAtIndexPath crash font(%ld)", (long)testIndex];
    DebugLog(@"%@", rail);
    ChatBaseTableViewCell<TIMElemAbleCell> *cell = [msg tableView:tableView style:[_receiver isC2CType] ? TIMElemCell_C2C : TIMElemCell_Group];
    [cell configWith:msg];
    cell.masksToBounds = YES;
    __weak __typeof(self)weakSelf = self;
    [cell.icon bk_whenTapped:^{
        [weakSelf cellWithMsg:msg];
    }];
    
    return cell;
}


- (void)preloadDataWithCurrentIndex:(NSInteger)currentIndex{
    NSInteger totalCount = _messageList.count;
    if (currentIndex == 5) {
         [self onRefresh];
    }
    
//    if ([self isSatisfyPreloadDataWithTotalCount:totalCount currentIndex:currentIndex]) {
//        [self onRefresh];
////        if (!self.tableView.mj_footer.hidden)
////        {
////            [self tableViewDidTriggerFooterRefresh];
////        }
//    }
}

- (BOOL)isSatisfyPreloadDataWithTotalCount:(NSInteger)totalCount currentIndex:(NSInteger)currentIndex{
    //    NSLog(@"currentIndex self.viewModel.dataSource.count == %lu",currentIndex % self.viewModel.dataSource.count);
    
    return  ((currentIndex == totalCount - PreloadMinCount) && (currentIndex >= PreloadMinCount));
}


-(void) cellWithMsg:(IMAMsg *)msg
{
    if (![msg isMineMsg])
    {
        IMAUser *user =  [msg getSender];
        IMAConversation *conversation =  [[IMAPlatform sharedInstance].conversationMgr chatWith:user];
        MHMomentViewModel *viewModel = [[MHMomentViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelIsFootPrint:@(true),MHViewModelTitleKey:isEquaalCurrentUserId(user.userId)?@"我的足迹":@"Ta的足迹",MHViewModelConversation:conversation}];
        viewModel.userId = [user.userId intValue];
        viewModel.imUser = user;
        [self.viewModel.services pushViewModel:viewModel animated:YES];
    }
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}


-(MHMoment *)momentWithMsg:(IMAMsg *)msg
{
    MHMoment *original;
    TIMCustomElem *customElem= [msg.msg getElem:0];
    if(![customElem isKindOfClass:[TIMCustomElem class]])
    {
        return nil;
    }
    NSDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:customElem.data options:NSJSONReadingMutableContainers error:nil];
    NSString *dict = [dictJson objectForKey:@"actionParam"];
    if (!dict) {
        return nil;
    }
    NSData *objectData = [dict dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                                         options:NSJSONReadingMutableContainers
                                                           error:nil];
    if (dict) {
        MHMoment *moment = [MHMoment yy_modelWithJSON:json];
        original = moment;
    }else
    {
        original = nil;
    }
    return original;
}

#pragma mark- BaseCell deleteCell
- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput sendMsg:(IMAMsg *)text
{
    [self sendMsg:text];
    NSMutableArray *elems = [NSMutableArray array];
    for (int index =0 ; index<text.msg.elemCount; index++ )
    {
        [elems addObject:[text.msg getElem:index]];
    }
    NSLog(@"%d",text.msg.elemCount);
}

- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput willSendMsg:(IMAMsg *)msg
{
    if (msg)
    {
        [UIView setAnimationsEnabled:NO];
        [_tableView beginUpdates];
        NSArray *newaddMsgs = [_conversation appendWillSendMsg:msg completion:nil];
        
        NSMutableArray *array = [NSMutableArray array];
        for (IMAMsg *newmsg in newaddMsgs)
        {
            NSInteger idx = [_messageList indexOfObject:newmsg];
            NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
            [array addObject:index];
        }
        [_tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationNone];
        [_tableView endUpdates];//UITableViewRowAnimationNone
        [UIView setAnimationsEnabled:YES];
        [self scrollBottom];
    }
}

- (void)onReplaceDelete:(NSArray *)replaceMsgs
{
    if (replaceMsgs.count)
    {
        [UIView setAnimationsEnabled:NO];
        [_tableView beginUpdates];
        NSMutableArray *addIndexs = [NSMutableArray array];
        for (IMAMsg *msg in replaceMsgs)
        {
            NSInteger index = [_messageList indexOfObject:msg];
            [addIndexs addObject:[NSIndexPath indexPathForRow:index inSection:0]];
        }
        // 说明只是替换最后一个
        [_tableView reloadRowsAtIndexPaths:addIndexs withRowAnimation:UITableViewRowAnimationNone];
        [_tableView endUpdates];
         [UIView setAnimationsEnabled:YES];
        [self scrollBottom];
    }
}

- (void)onChatInput:(UIView<ChatInputAbleView> *)chatInput replaceWith:(IMAMsg *)newMsg oldMsg:(IMAMsg *)msg
{
    if (msg)
    {
        __weak __typeof(self)weakSelf = self;
        TIMOfflinePushInfo *info =  [TIMOfflinePushInfo new];
        info.desc = _conversation.type == TIM_GROUP ? @"" : @"[语音]";
         info.pushFlag =   _conversation.type == TIM_GROUP ? TIM_OFFLINE_PUSH_NO_PUSH :  TIM_OFFLINE_PUSH_DEFAULT ;
        [newMsg.msg setOfflinePushInfo:info];
        [_conversation replaceWillSendMsg:msg with:newMsg completion:^(NSArray *imamsgList, BOOL succ) {
            if (succ)
            {
                [weakSelf onReplaceDelete:imamsgList];
            }
        }];
    }
}



@end
